<template>
  <div class="employees-container">
    <div class="app-container">

      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=21676876876')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportEpy">excel导出</el-button>
          <el-button type="primary" size="small" @click="add">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格 -->
      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="tableData">
          <el-table-column label="姓名" prop="username" />
          <!-- 头像 -->
          <el-table-column prop="staffPhoto">
            <template slot-scope="scope">
              <img v-imgerr class="staff" :src="scope.row.staffPhoto">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ handleEpy(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" :formatter="handleTime"/>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :page-size="size" :total="total" layout="prev, pager, next" @current-change="pageChange" />
        </div>

      </el-card>

      <!-- 弹窗 -->
      <el-dialog title="新增员工" :visible="showDialog" @close="close">
        <!-- 表单 -->
        <el-form ref="Form" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="formData.username" style="width:50%" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="formData.mobile" style="width:50%" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker v-model="formData.timeOfEntry" style="width:50%" placeholder="请选择入职时间" />
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="formData.formOfEmployment" style="width:50%" placeholder="请选择" >
              <el-option
                v-for="item in hireType"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="formData.workNumber" style="width:50%" placeholder="请输入工号"  />
          </el-form-item>
          <el-form-item label="部门" prop="departmentName">
            <el-input v-model="formData.departmentName" style="width:50%" placeholder="请选择部门" @click.native="treeShow = ! treeShow"/>
            <el-tree v-if="treeShow" :data="treeData" :props="props" @node-click="nodeClick"/>
          </el-form-item>
          <el-form-item label="转正时间" prop="correctionTime">
            <el-date-picker v-model="formData.correctionTime" style="width:50%" placeholder="请选择转正时间" />
          </el-form-item>
          <el-form-item>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageList, del, add } from '@/api/employees' // 员工
import { list } from '@/api/departments' // 组织机构

import epy from '@/constant/employees'

import dayjs from 'dayjs'
import { arrToTree } from '@/utils/index'
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      loading: false,
      page: 1,
      size: 10,
      // ***************** 弹窗
      formData: {
        username: '', // 用户名
        mobile: '', // 手机号
        formOfEmployment: '', // 聘用形式
        workNumber: '', // 工号
        departmentName: '', // 部门
        timeOfEntry: '', // 入职时间
        correctionTime: '' // 转正时间
      },
      rules: {
        username: [
          { required: true, message: '用户姓名不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 4, message: '用户姓名为1-4位', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: ['blur', 'change'] },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
        ],
        formOfEmployment: [
          { required: true, message: '聘用形式不能为空', trigger: ['blur', 'change'] }
        ],
        workNumber: [
          { required: true, message: '工号不能为空', trigger: ['blur', 'change'] }
        ],
        departmentName: [
          { required: true, message: '部门不能为空', trigger: ['blur', 'change'] }
        ],
        timeOfEntry: [
          { required: true, message: '请选择入职时间', trigger: ['blur', 'change'] }
        ]
      },
      showDialog: false,
      // ************ 表单
      treeData: [],
      props: {
        // 本来要求名字：后面后台生气改了的名字  映射对应！依据文档！
        label: 'name',
        children: 'sons'
      },
      treeShow: false,
      hireType: epy.hireType // 聘用形式
    }
  },
  created() {
    this.get_list()
    this.get_treeList()
  },
  methods: {
    // 列表数据
    async get_list() {
      this.loading = true
      const { data } = await pageList(this.page, this.size)
      // console.log(data.rows)
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
    },
    // 分页功能
    pageChange(val) {
      this.page = val
      this.get_list()
    },
    // 枚举
    handleEpy(val) {
      const one = epy.hireType.find(item => val === item.id)
      return one ? one.value : '未知'
    },
    // 时间
    handleTime(row, column, cellValue, index) {
      return dayjs(cellValue).format('YYYY年MM月DD日')
    },
    // 删除
    del(id) {
      // 1、询问下：
      this.$confirm('确定删除此数据么?', '删除提示')
        .then(async() => {
          // 2、调用删除接口 传入id
          await del(id) // 把数据库里面数据删除了
          this.$message.success('删除成功')
          if (this.tableData.length === 1 && this.page > 1) {
            this.page-- // 回到上一页
          }

          // 3、重新调用列表
          this.get_list()
        })
        // .catch(() => {

      // })
    },
    // ************************  弹窗
    add() {
      this.showDialog = true
    },
    async exportEpy() {
      const { data } = await pageList(1, this.total)
      const arr = data.rows

      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      //  英中文对照表
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const newArr = [] // 所有行数据收集
      arr.forEach(one => {
        const newOne = []
        for (const cn_key in headersRelations) {
          const en_key = headersRelations[cn_key]
          let val = one[en_key]
          // 日期处理
          if (en_key === 'timeOfEntry' || en_key === 'correctionTime') {
            val = this.handleTime(null, null, val)
          }
          // 聘用方式
          if (en_key === 'formOfEmployment') {
            val = this.handleEpy(val)
          }
          // 把对应值 添加到新数组内
          newOne.push(val)
        }

        newArr.push(newOne)
      })

      //  4、执行导出
      import('@/vendor/Export2Excel')
        .then(excel => {
          excel.export_json_to_excel({
            header: headersArr,
            data: newArr, // 具体数据 必填
            filename: '全部员工数据列表', // 非必填
            autoWidth: true, // 非必填
            bookType: 'xlsx' // 非必填
          })
        })
    },
    // 关闭弹窗
    close() {
      this.showDialog = false
      // 重置表单
      this.$refs.Form.resetFields()

      this.formData = {
        username: '', // 用户名
        mobile: '', // 手机号
        formOfEmployment: '', // 聘用形式
        workNumber: '', // 工号
        departmentName: '', // 部门
        timeOfEntry: '', // 入职时间
        correctionTime: '' // 转正时间
      }
    },
    // ************************  表单
    // 获取树列表数据
    async get_treeList() {
      // 1、获取数据
      const { data } = await list()
      // 2、设置
      this.treeData = arrToTree(data.depts, '')
    },
    nodeClick(one) { // tree 点击被点击
      if (one.sons && one.sons.length > 0) return
      this.formData.departmentName = one.name
      this.treeShow = false
    },
    submit() { // 确认提交
      this.$refs.Form.validate(async(valid) => {
        if (valid) {
          await add(this.formData) // 2、准备新增api接口
          this.$message.success('新增成功')

          this.get_list()
          this.close()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
